<template>
  <div class="container">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        ref="crud"
        v-model="form"
        :upload-before="uploadBefore"
        :upload-after="uploadAfter"
        :before-open="beforeOpen"
        @row-del="rowDel"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @search-change="searchChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @on-load="onLoad"
      >
        <template slot="excelTemplateForm">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
        <template slot="errorDataTemplateForm">
          <el-button type="warning" @click="downloadErrorData">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            size="small"
            class="none-border"
            @click.stop="handleManage(scope.row, scope.index)"
            >字段时间管理
          </el-button>
        </template>
        <template #batchType="scope">
          <el-tag type="warning">{{ scope.row.batchType }}</el-tag>
        </template>
      </avue-crud>

      <el-dialog title="字段时间管理" append-to-body :visible.sync="timeBox" width="800px">
        <avue-form :option="timeOption" ref="timeForm" v-model="timeForm" @submit="timeSubmit">
        </avue-form>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {getList, getDetail, add, update, updateTime, remove} from "@/api/business/batch";
import { mapGetters } from "vuex";
import {getToken} from '@/util/auth';
import {exportBlob} from "@/api/common";

export default {
  name: "batch",
  data() {
    return {
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      query: {},
      loading: true,
      form:{
        id: ''
      },
      templateName: '集采新增固定模板.xlsx',
      data: [],
      option: {
        stripe: true,
        searchBtn: true,
        border: true,
        viewBtn: false,
        index: true,
        indexLabel: '序号',
        emptyBtn: false,
        searchMenuSpan: 1,
        searchBtnText: "查询",
        refreshBtn: false,
        searchShowBtn: false,
        columnBtn: false,
        align: "center",
        labelWidth:150,
        column: [
          {
            label: "批次名称",
            prop: "batchName",
            search: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入批次名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "批次类型",
            prop: "batchType",
            span: 24,
            search: true,
            type: "radio",
            dicData: [{ label: "药品批次",value:"药品批次" }, { label: "医用耗材批次",value:"医用耗材批次" }],
            rules: [
              {
                required: true,
                message: "请选择批次类型",
                trigger: "blur",
              },
            ],
          },
          {
            label: "模板文件",
            prop: "imgUrl",
            type: "upload",
            span: 24,
            drag: true,
            loadText: '模板上传中，请稍等',
            fileText:'选取导入数据文件',
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/batchItem/importNew",
            data: {
              batchId: ''
            },
            hide: true,
          },
          {
            label: '模板下载',
            prop: 'excelTemplate', 
            formslot:true,
            hide: true,
            span: 12,
          },
          {
            label: '错误数据下载',
            prop: 'errorDataTemplate',
            formslot:true,
            hide: true,
            span: 12,
          }
        ],
      },
      timeBox: false,
      timeForm: {
        title: "约定量（万支/万袋/万片）",
        title1: "合同签订量（盒）",
        title2: "实际配送数量"
      },
      timeOption: {
        emptyBtn: false,
        labelWidth:150,
        column: [
          {label: "", labelWidth:0, type: 'title', prop: "title", span: 24},
          {
            label: "开始时间",
            prop: "appointAmountStart",
            type: "datetime",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",
            span: 12,
            rules: [{
              required: true,
              message: "请输入开始时间",
              trigger: "blur"
            }],
          },
          {
            label: "结束时间",
            prop: "appointAmountEnd",
            type: "datetime",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",
            span: 12,
            rules: [{
              required: true,
              message: "请输入开始时间",
              trigger: "blur"
            }],
          },
          {label: "", labelWidth:0, type: 'title', prop: "title1", span: 24},
          {
            label: "开始时间",
            prop: "contractBoxStart",
            type: "datetime",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",
            span: 12,
            rules: [{
              required: true,
              message: "请输入开始时间",
              trigger: "blur"
            }],
          },
          {
            label: "结束时间",
            prop: "contractBoxEnd",
            type: "datetime",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",
            span: 12,
            rules: [{
              required: true,
              message: "请输入开始时间",
              trigger: "blur"
            }],
          },
          {label: "", labelWidth:0, type: 'title', prop: "title2", span: 24},
          {
            label: "开始时间",
            prop: "actualDeliverStart",
            type: "datetime",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",
            span: 12,
            rules: [{
              required: true,
              message: "请输入开始时间",
              trigger: "blur"
            }],
          },
          {
            label: "结束时间",
            prop: "actualDeliverEnd",
            type: "datetime",
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd hh:mm:ss",
            span: 12,
            rules: [{
              required: true,
              message: "请输入开始时间",
              trigger: "blur"
            }],
          },
        ]
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  methods: {
    beforeOpen(done, type) {
      done();
    },
    uploadBefore (file, done, loading, column) {
      column.data.batchId = this.form.id;
      done();
    },
    handleTemplate() {
      exportBlob(`/api/medpurBatch/download?${this.website.tokenHeader}=${getToken()}&templateName=${this.templateName}`).then((response) => {
        if(response.data.size > 0){
          let url = window.URL.createObjectURL(response.data);
          let a = document.createElement("a");
          document.body.appendChild(a);
          a.href = url;
          a.download = this.templateName;
          a.click();
          window.URL.revokeObjectURL(url);
        }else{
          this.$message.warning('模板文件不存在!');
        }
      });
    },
    downloadErrorData() {
      exportBlob(`/api/medpurBatch/downloadErrorData?${this.website.tokenHeader}=${getToken()}&batchId=${this.form.id}`).then((response) => {
        if(response.data.size > 0){
          let url = window.URL.createObjectURL(response.data);
          let a = document.createElement("a");
          document.body.appendChild(a);
          a.href = url;
          a.download = "集采批次管理批量导入错误明细.xlsx";
          a.click();
          window.URL.revokeObjectURL(url);
        }else{
          this.$message.warning('模板文件不存在!');
        }
      });
    },
    uploadAfter(res, done) {
      if (res.success) {
        this.form.id = res.data;
        console.log('form',this.form);
        this.$message({
          type: "success",
          message: res.msg
        });
      }
      done();
    },
    rowSave(row, done, loading) {
      if (row.id === undefined || row.id === '') {
        this.$message({
          type: "error",
          message: "请上传模板文件！"
        });
        loading();
      } else {
        add(row).then(res => {
          this.onLoad(this.page);
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      }
    },
    rowUpdate(row, index, done, loading) {
      console.log('rowUpdate',row);
      update(row).then(res => {
        this.onLoad(this.page);
        if (res.data.success) {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    handleManage(row) {
      this.timeBox = true;
      this.timeForm = row;
      this.timeForm.title = "约定量(片/袋/支)";
      this.timeForm.title1 = "合同量(片/袋/支)";
      this.timeForm.title2 = "实际采购(片/袋/支)";
    },
    timeSubmit(form, done) {
      let date1 = new Date(form.appointAmountStart);
      let date2 = new Date(form.appointAmountEnd);
      let isAfter = date1.getTime() >= date2.getTime();
      let date3 = new Date(form.contractBoxStart);
      let date4 = new Date(form.contractBoxEnd);
      let date5 = new Date(form.actualDeliverStart);
      let date6 = new Date(form.actualDeliverEnd);
      let isAfter1 = date3.getTime() >= date4.getTime();
      let isAfter2 = date5.getTime() >= date6.getTime();
      if (isAfter || isAfter1 || isAfter2) {
        this.$message({
          type: "error",
          message: "每项结束时间必须大于开始时间！"
        });
        done();
      } else {
        updateTime(form).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          done();
          console.log(error);
        });
        this.timeBox = false;
        this.$refs.timeForm.resetForm();
      }
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    }
  },
};
</script>

<style lang="scss" scoped></style>
